<template>
  <div>
    <Card :bordered="false" dis-hover class="ivu-mt box">
      <Form
        ref="formValidate"
        :model="formValidate"
        :label-width="labelWidth"
        :label-position="labelPosition"
        class="tabform"
        @submit.native.prevent
      >
        <div class="acea-row">
          <FormItem :label="$t('page.stock.select_date')+'：'">
            <DatePicker type="month" :locale="customLocale" placeholder="Select month" @on-change="onchangeTime" style="width: 200px;margin-right: 20px;" />
          </FormItem>

          <FormItem :label="$t('page.product.details')+$t('page.order.type')+'：'" v-if="currentTab === '2'">
            <Select v-model="formValidate.detail_type" filterable style="width: 250px;margin-right: 20px;">
              <Option value="order.income">{{ $t('page.order.order') + $t('bili.income') }}</Option>
              <Option value="storage.fee">{{$t('bili.storage')+$t('page.order.fee') }}</Option>
              <Option value="unloading.fee">{{$t('bili.unloading')+$t('page.order.fee') }}</Option>
              <Option value="ob.fee">{{$t('page.order.ob')+$t('page.order.fee') }}</Option>
              <Option value="shownroom.fee">{{$t('bili.shownroom')+$t('page.order.fee') }}</Option>
              <Option value="special.charges">{{$t('bili.special')+$t('page.order.fee') }}</Option>
            </Select>
          </FormItem>

          <FormItem :label="$t('page.stock.warehouse')+'：'" v-if="currentTab === '2'">
            <Select
                v-model="formValidate.warehouse_name"
                clearable
                style="width:200px;"
            >
              <Option
                  v-for="item in stockNameList"
                  :value="item.value"
                  :key="item.value"
              >{{ item.label }}</Option>
            </Select>
          </FormItem>

          <Button v-if="currentTab === '2'" type="primary" @click="onchangeDetailType" class="ml10">{{$t('page.stock.search')}}</Button>


        </div>

      </Form>
    </Card>

    <Card :bordered="false" dis-hover class="ive-mt tablebox">
      <div class="product_tabs tabbox">
        <Tabs @on-click="onClickTab" v-model="currentTab">
          <TabPane
              v-for="(item, index) in headTab"
              :key="index"
              :label="item.title"
              :name="item.name"
          ></TabPane>
        </Tabs>
      </div>
      <div class="btnbox"></div>
      <div v-show="currentTab === '1'" class="table">
        <el-result v-if="formValidate.data == ''"  icon="warning" :title="$t('bili.no_selected')"></el-result>
        <Row v-else>
          <Col span="12">
            <div class="section">
              <div class="title">{{ $t('sliderMenu.bill') }}</div>
              <ul class="list">
                <!--                <li class="item">-->
                <!--                  <Icon type="logo-usd" />-->
                <!--                </li>-->

                <li class="item">
                  <div>{{$t('bili.collection')}} {{$t('page.order.total')}}：</div>
                  <div class="value">
                    <Numeral :value="SettlementSummary.ending_balance" format="0,0.00">
                      <template #prefix>
                        <strong>$</strong>
                      </template>
                    </Numeral>
                  </div>
                </li>
                <li class="item">
                  <div>{{$t('bili.sales')}} {{$t('bili.credits')}}：</div>
                  <div class="value">
                    <Numeral :value="SettlementSummary.sales_revenue" format="0,0.00">
                      <template #prefix>
                        <strong>$</strong>
                      </template>
                    </Numeral>
                  </div>
                </li>
                <li class="item">
                  <div>{{$t('bili.costs')}}：</div>
                  <div class="value">
                    <Numeral :value="SettlementSummary.costs" format="0,0.00">
                      <template #prefix>
                        <strong>$</strong>
                      </template>
                    </Numeral>
                  </div>
                </li>
                <li class="item" v-if="SettlementSummary.type ==2">
                  <Button type="primary" @click="confirm(SettlementSummary)">{{$t('page.product.confirm')}} {{$t('sliderMenu.bill')}}</Button>
                </li>
                <li class="item" v-if="SettlementSummary.type ==2">
                  <Button type="primary" @click="confirm(SettlementSummary)">驳回 {{$t('sliderMenu.bill')}}</Button>
                </li>
                <li class="item" >
                  <Button type="primary" @click="exportBili(SettlementSummary.id)">Excel</Button>
                </li>
                <li class="item" v-if="SettlementSummary.type ==4"><a :href="SettlementSummary.file_url" target="_blank">{{ $t('bili.paid_evidence') }}</a></li>
              </ul>
            </div>
          </Col>
          <Col span="20" offset="2" style="padding-top: 10px;">
            <Steps :current="SettlementSummary.type -1">
              <Step :title="$t('bili.in_progress')" :content="this.formattedDate(SettlementSummary.in_progress_time)"></Step>
              <Step :title="$t('bili.seller_confirming')" :content="(SettlementSummary.type -1) >= 1?this.formattedDate(SettlementSummary.in_settlement_time):''"></Step>
              <Step :title="$t('bili.pending_payment')" :content="(SettlementSummary.type -1) >= 2?this.formattedDate(SettlementSummary.settled_time):''"></Step>
              <Step :title="$t('bili.paid')" :content="(SettlementSummary.type -1) >= 3?this.formattedDate(SettlementSummary.paid_time):''"></Step>
            </Steps>
          </Col>
          <Col span="12">
            <div style="padding: 20px;">
              <Card :bordered="false"  class="ivu-mt" style="width:100%;height: 500px;" shadow bordered>
                <template #title>{{$t('bili.sales')}} {{$t('bili.credits')}}</template>
                <div class="sales">
                  <div class="sales-title"></div>
                  <div class="sales-debits">{{$t('bili.debits')}}</div>
                  <div class="sales-credits">{{$t('bili.credits')}}</div>
                </div>

                <div class="sales" v-for="(val, i) in SettlementSummary.system_supplier_bill_summary" :key="i" v-if="val.type == 'sales'">
                  <div class="sales-title">{{val.title}}</div>
                  <div class="sales-debits">
                    <Numeral :value="val.debits" format="0,0.00">
                      <template #prefix>
                        <strong>$</strong>
                      </template>
                    </Numeral>
                  </div>
                  <div class="sales-credits">
                    <Numeral :value="val.credits" format="0,0.00">
                      <template #prefix>
                        <strong>$</strong>
                      </template>
                    </Numeral>
                  </div>
                </div>

                <div class="sales sales-bottom">
                  <div class="sales-title">{{$t('bili.credits')}}</div>
                  <div class="sales-debits"></div>
                  <div class="sales-credits">
                    <Numeral :value="this.sales_subtotal" format="0,0.00">
                      <template #prefix>
                        <strong>$</strong>
                      </template>
                    </Numeral>
                  </div>
                </div>

              </Card>
            </div>
          </Col>
          <Col span="12">
            <div style="padding: 20px;">
              <Card :bordered="false"  class="ivu-mt" style="width:100%;height: 500px;" shadow bordered>
                <template #title>{{$t('page.order.fee')}}</template>
                <div class="sales">
                  <div class="sales-title"></div>
                  <div class="sales-debits">{{ $t('bili.debits') }}</div>
                  <div class="sales-credits"></div>
                </div>

                <div class="sales" v-for="(val, i) in SettlementSummary.system_supplier_bill_summary" :key="i" v-if="val.type == 'costs'">
                  <div class="sales-title">{{val.title}}</div>
                  <div class="sales-debits">
                    <Numeral :value="val.debits" format="0,0.00">
                      <template #prefix>
                        <strong>$</strong>
                      </template>
                    </Numeral>
                  </div>
                  <div class="sales-credits"></div>
                </div>

                <div class="sales sales-bottom">
                  <div class="sales-title">{{ $t('bili.subtotal') }}</div>
                  <div class="sales-debits">
                    <Numeral :value="this.costs_subtotal" format="0,0.00">
                      <template #prefix>
                        <strong>$</strong>
                      </template>
                    </Numeral>
                  </div>
                  <div class="sales-credits"></div>
                </div>
              </Card>
            </div>
          </Col>
        </Row>
      </div>
      <div v-show="currentTab === '2'" class="table">

        <table class="price-table" v-if="formValidate.detail_type == 'order.income' && orderList.length >= 1">
          <thead>
          <tr>
            <th></th>
            <th>{{ $t('page.order.order') }} {{ $t('bili.credits') }}</th>
            <th>{{ $t('page.order.ob') }} {{ $t('page.order.fee') }}</th>
            <th>{{ $t('page.order.service') }} {{ $t('page.order.fee') }}</th>
            <th>{{ $t('page.order.shipping') }} {{ $t('page.order.fee') }}</th>
          </tr>
          </thead>
          <tbody >
          <tr>
            <td>
              {{ $t('bili.all_total') }}
            </td>
            <td>
              <Numeral :value="SettlementSummary.sales_revenue" format="0,0.00">
                <template #prefix>
                  <strong>$</strong>
                </template>
              </Numeral>
            </td>
            <td v-for="(item,index) in SettlementSummary.system_supplier_bill_summary" :key="index" v-if="item.en_title == 'ob_fee'">
              <Numeral :value="item.debits" format="0,0.00">
                <template #prefix>
                  <strong>$</strong>
                </template>
              </Numeral>
            </td>
            <td v-for="(item,index) in SettlementSummary.system_supplier_bill_summary" :key="index" v-if="item.en_title == 'halfwarehouse_service_fee'">
              <Numeral :value="item.debits" format="0,0.00">
                <template #prefix>
                  <strong>$</strong>
                </template>
              </Numeral>
            </td>
            <td v-for="(item,index) in SettlementSummary.system_supplier_bill_summary" :key="index" v-if="item.en_title == 'shipping_fee'">
              <Numeral :value="item.debits" format="0,0.00">
                <template #prefix>
                  <strong>$</strong>
                </template>
              </Numeral>
            </td>
          </tr>
          </tbody>
        </table>

        <table class="price-table" v-if="formValidate.detail_type == 'storage.fee' && orderList.length >= 1">
          <thead>
          <tr>
            <th></th>
            <th>{{ $t('bili.storage') }} {{ $t('page.order.fee') }}</th>
          </tr>
          </thead>
          <tbody>
          <tr>
            <td>
              {{ $t('bili.all_total') }}
            </td>
            <td v-for="(val, i) in SettlementSummary.system_supplier_bill_summary" :key="i" v-if="val.en_title == 'storage_fee'">
              <Numeral :value="val.debits" format="0,0.00">
                <template #prefix>
                  <strong>$</strong>
                </template>
              </Numeral>
            </td>
          </tr>
          </tbody>
        </table>

        <table class="price-table" v-if="formValidate.detail_type == 'unloading.fee' && orderList.length >= 1">
          <thead>
          <tr>
            <th></th>
            <th>{{ $t('page.stock.inbound') }} {{ $t('page.order.fee') }}</th>
          </tr>
          </thead>
          <tbody >
          <tr>
            <td>
              {{ $t('bili.all_total') }}
            </td>
            <td v-for="(val, i) in SettlementSummary.system_supplier_bill_summary" :key="i" v-if="val.en_title == 'unloading_fee'">
              <Numeral :value="val.debits" format="0,0.00">
                <template #prefix>
                  <strong>$</strong>
                </template>
              </Numeral>
            </td>
          </tr>
          </tbody>
        </table>

        <table class="price-table" v-if="formValidate.detail_type == 'ob.fee' && orderList.length >= 1">
          <thead>
          <tr>
            <th></th>
            <th>{{ $t('page.stock.outbound') }} {{ $t('page.order.fee') }}</th>
          </tr>
          </thead>
          <tbody >
          <tr>
            <td>
              {{ $t('bili.all_total') }}
            </td>
            <td v-for="(val, i) in SettlementSummary.system_supplier_bill_summary" :key="i" v-if="val.en_title == 'ob_fee'">
              <Numeral :value="val.debits" format="0,0.00">
                <template #prefix>
                  <strong>$</strong>
                </template>
              </Numeral>
            </td>
          </tr>
          </tbody>
        </table>

        <table class="price-table" v-if="formValidate.detail_type == 'shipping.fee' && orderList.length >= 1">
          <thead>
          <tr>
            <th></th>
            <th>{{ $t('page.stock.shipping') }} {{ $t('page.order.fee') }}</th>
          </tr>
          </thead>
          <tbody >
          <tr>
            <td>
              {{ $t('bili.all_total') }}
            </td>
            <td v-for="(val, i) in SettlementSummary.system_supplier_bill_summary" :key="i" v-if="val.en_title == 'shipping_fee'">
              <Numeral :value="val.debits" format="0,0.00">
                <template #prefix>
                  <strong>$</strong>
                </template>
              </Numeral>
            </td>
          </tr>
          </tbody>
        </table>

        <table class="price-table" v-if="formValidate.detail_type == 'special.charges' && orderList.length >= 1">
          <thead>
          <tr>
            <th></th>
            <th>{{ $t('page.order.fee') }}</th>
          </tr>
          </thead>
          <tbody >
          <tr>
            <td>
              {{ $t('bili.all_total') }}
            </td>
            <td v-for="(val, i) in SettlementSummary.system_supplier_bill_summary" :key="i" v-if="val.en_title == 'special_charges'">
              <Numeral :value="val.debits" format="0,0.00">
                <template #prefix>
                  <strong>$</strong>
                </template>
              </Numeral>
            </td>
          </tr>
          </tbody>
        </table>



        <Table
            :columns="columns"
            :data="orderList"
            height="600"
            ref="table"
            class="mt25"
            :loading="loading"
            highlight-row
            :no-userFrom-text="$t('page.product.no_data')"
        >

          <template #created_at="{ row }">
            <strong>{{ formatTimeNative(row.created_at) }}</strong>
          </template>

          <template #month="{ row }">
            <p>{{ formValidate.data}}</p>
          </template>

          <template slot-scope="{ row }" slot="is_pay">
            <Tag color="gold" v-if="row.is_pay == 0">{{ $t('page.order.unpaid') }}</Tag>
            <Tag color="green" v-if="row.is_pay == 1">{{ $t('page.order.paid') }}</Tag>
          </template>
          <template slot-scope="{ row }" slot="is_mention">
            <Tag color="gold" v-if="row.is_mention == 1">{{ $t('page.order.fulfilled') }}</Tag>
            <Tag color="green" v-if="row.is_mention == 0">{{ $t('page.order.unfulfilled') }}</Tag>
          </template>
          <template slot-scope="{ row }" slot="location">
            <span v-if="row.warehouse_name =='1791498718751334401'">CA 5005</span>
            <span v-if="row.warehouse_name =='101816795504'">Houston</span>
            <p></p>
          </template>

          <template slot-scope="{ row }" slot="ob_no">
            <p>{{ row.ob_no }}</p>
          </template>

          <template slot-scope="{ row }" slot="discounted_total_set">
            <span>
              <Numeral :value="row.discounted_total_set" format="0,0.00">
                  <template #prefix>
                      <strong>$</strong>
                  </template>
              </Numeral>
            </span>
          </template>

          <template slot-scope="{ row }" slot="cost">
            <span>
              <Numeral :value="row.cost" format="0,0.00">
                  <template #prefix>
                      <strong>$</strong>
                  </template>
              </Numeral>
            </span>
          </template>


          <template slot-scope="{ row }" slot="ob_fee">
            <span>
              <Numeral :value="row.ob_fee" format="0,0.00">
                  <template #prefix>
                      <strong>$</strong>
                  </template>
              </Numeral>
            </span>
          </template>

          <template slot-scope="{ row }" slot="shipping_fee">
            <span>
              <Numeral :value="row.shipping_fee" format="0,0.00">
                  <template #prefix>
                      <strong>$</strong>
                  </template>
              </Numeral>
            </span>
          </template>

          <template slot-scope="{ row }" slot="commission">
            <span>
              <Numeral :value="row.commission" format="0,0.00">
                  <template #prefix>
                      <strong>$</strong>
                  </template>
              </Numeral>
            </span>
          </template>

          <template slot-scope="{ row }" slot="put_price">
            <span>
              <Numeral :value="row.put_price" format="0,0.00">
                  <template #prefix>
                      <strong>$</strong>
                  </template>
              </Numeral>
            </span>
          </template>


          <template slot-scope="{ row }" slot="amount">
            <span>
              <Numeral :value="row.amount" format="0,0.00">
                  <template #prefix>
                      <strong>$</strong>
                  </template>
              </Numeral>
            </span>
          </template>

          <template slot-scope="{ row }" slot="compute">
            <span>{{ row.compute == 'increment'? $t('bili.add'):$t('bili.reduce') }}</span>
          </template>

          <template slot-scope="{ row, index }" slot="action">
            <a @click="Info(row)">{{$t('page.order.detail')}}</a>
            <Divider type="vertical" />
            <a @click="exportWarehouseBili(row.id)">{{$t('page.stock.export')}}</a>
          </template>

        </Table>
        <div class="acea-row row-right page">
          <Page
              :total="total"
              :current.sync="formValidate.page"
              @on-change="pageChange"
              :page-size="formValidate.limit"
          />
        </div>
      </div>

    </Card>
    <warehouse-detail ref="commission"></warehouse-detail>
  </div>
</template>

<script>
import exportExcel from '@/utils/newToExcel.js';
import commissionDetails from '../components/commissionDetails';
import {exportfundRecordApi, exportWarehouseBillInfo} from '@/api/capital';
import zhCNiView from 'view-design/dist/locale/zh-CN';
import timeOptions from '@/utils/timeOptions2';
import {
  exportSupplierSummaryInfo,
  systemSupplierBillSettlementSummary,
  systemSupplierBillSettlementSummaryList
} from "@api/finance";
import warehouseDetail from "@/pages/capital/components/warehouseDetail.vue";
export default {
  name: 'bill',
  components: {
    warehouseDetail,
    commissionDetails,
  },
  data() {
    return {
      currentTab: "1",
      total: 0,
      loading: false,
      tab: 'day',
      options: timeOptions,
      customLocale: zhCNiView,
      columns:[],
      sales_subtotal:0,
      costs_subtotal:0,
      SettlementSummary:{},
      infor:{},
      stockNameList: [
        {
          value: '1791498718751334401',
          label: 'CA5005'
        },
        {
          value: '101816795504',
          label: 'Houston'
        }
      ],
      orderList: [],
      formValidate: {
        data: '',
        detail_type:"",
        page: 1,
        limit: 20,
      },
      timeVal: "",
    };
  },
  computed: {
    labelWidth() {
      return this.isMobile ? 0 : 80;
    },
    labelPosition() {
      return this.isMobile ? 'top' : 'left';
    },
    headTab(){
      return [
        { title: $t('sliderMenu.bill'), name: "1" },
        { title: $t('sliderMenu.bill_record'), name: "2" },
      ]
    },
    orderIncomeAColumns(){
     return [
       {
         title: $t('page.order.date'),
         key: 'created_at',
         slot: 'created_at',
         width: 90,
       },
       {
         title: $t('page.order.order_no'),
         key: 'order_no',
         minWidth: 100,
       },
      {
         title: $t('page.product.product_list'),
         key: 'name',
         minWidth: 200,
       },
       {
         title: 'SKU',
         key: 'sku',
         minWidth: 120,
       },
       {
         title: $t('page.order.order') + $t('bili.credits'),
         slot: 'discounted_total_set',
         minWidth: 80,
       },
       {
         title: $t('page.order.payment') + $t('page.stock.status') ,
         slot: 'is_pay',
         minWidth: 80,
       },
       {
         title: $t('page.order.fulfillment') + $t('page.stock.status'),
         slot: 'is_mention',
         minWidth: 80,
       },
       {
         title: $t('page.stock.warehouse'),
         slot: 'location',
         minWidth: 80,
       },
       {
         title: $t('page.stock.outbound_order_no'),
         slot: 'ob_no',
         minWidth: 120,
       },
       {
         title: $t('page.stock.outbound')+ $t('page.order.fee'),
         slot: 'ob_fee',
         minWidth: 80,
       },
       {
         title: $t('page.order.service') + $t('page.order.fee'),
         slot: 'commission',
         minWidth: 80,
       },
       {
         title:  $t('page.order.shipping') + $t('page.order.fee'),
         slot: 'shipping_fee',
         minWidth: 80,
       },
     ]
    },
    orderIncomeBColumns(){
      return [
        {
          title: $t('page.order.date'),
          key: 'created_at',
          slot: 'created_at',
          width: 90,
        },
        {
          title: $t('page.order.order_no'),
          key: 'order_no',
          minWidth: 100,
        },
        {
          title: $t('page.customer.customer_name'),
          key: 'customer_name',
          minWidth: 150,
        },
        {
          title: $t('page.product.product_list'),
          key: 'name',
          minWidth: 200,
        },
        {
          title: 'SKU',
          key: 'sku',
          minWidth: 120,
        },
        {
          title: $t('page.order.order') + $t('bili.credits'),
          slot: 'discounted_total_set',
          minWidth: 80,
        },
        {
          title: $t('page.order.payment') + $t('page.stock.status') ,
          slot: 'is_pay',
          minWidth: 80,
        },
        {
          title: $t('page.order.fulfillment') + $t('page.stock.status'),
          slot: 'is_mention',
          minWidth: 80,
        },
        {
          title: $t('page.stock.warehouse'),
          slot: 'location',
          minWidth: 80,
        },
        {
          title: $t('page.stock.outbound_order_no'),
          slot: 'ob_no',
          minWidth: 120,
        },
        {
          title: $t('page.stock.outbound')+ $t('page.order.fee'),
          slot: 'ob_fee',
          minWidth: 80,
        },
        {
          title: $t('page.order.service') + $t('page.order.fee'),
          slot: 'commission',
          minWidth: 80,
        },
        {
          title:  $t('page.order.shipping') + $t('page.order.fee'),
          slot: 'shipping_fee',
          minWidth: 80,
        },
      ]
    },
    storageFeeColumns(){
      return [
        {
          title: $t('page.stock.date'),
          key: 'time',
          width: 150,
        },
        {
          title: $t('page.order.name'),
          key: 'name',
          minWidth: 150,
        },
        {
          title: $t('page.order.fee'),
          key: 'amount',
          slot: 'amount',
          minWidth: 150,
        },
        {
          title: $t('page.order.operate'),
          slot: 'action',
          minWidth: 120,
          align: 'center',
        },
      ]
    },
    obFeeColumns(){
      return [
        {
          title: $t('page.stock.date'),
          key: 'archiving_period',
          width: 150,
        },
        {
          title: $t('page.stock.outbound_order_no'),
          key: 'out_bounding_biz_no',
          minWidth: 150,
        },{
          title: $t('page.order.name'),
          key: 'fees_item_name',
          minWidth: 150,
        },
        {
          title: $t('page.order.fee'),
          key: 'cost',
          slot: 'cost',
          minWidth: 150,
        }
      ]

    },
    unloadingFeeColumns(){
      return[
        {
          title: $t('page.stock.date'),
          key: 'receive_time',
          width: 150,
        },
        {
          title: $t('page.stock.inbound_order'),
          key: 'biz_no',
          minWidth: 150,
        },
        {
          title: $t('page.stock.title'),
          key: 'fees_item_name',
          minWidth: 150,
        },
        {
          title: $t('page.order.fee'),
          key: 'cost',
          slot: 'cost',
          minWidth: 150,
        }
      ]
    },
    specialFeeColumns(){
     return [
       {
         title: $t('page.order.name'),
         key: 'title',
         minWidth: 150,
       },
       {
         title: $t('page.stock.note'),
         key: 'remarks',
         minWidth: 150,
       },
       {
         title: $t('page.order.fee'),
         key: 'cost',
         slot:"cost",
         minWidth: 150,
       },
       {
         title: '计算方式',
         key: 'compute',
         slot:"compute",
         minWidth: 150,
       },

     ]
    },
    shownroomFeeColumns(){
      return [
        {
          title: $t('page.order.date'),
          key: 'month',
          slot:'month',
          width: 150,
        },
        {
          title: $t('page.supplier.space'),
          key: 'area',
          minWidth: 150,
        },
        {
          title: $t('page.order.location'),
          key: 'name',
          minWidth: 150,
        },
        {
          title: $t('page.supplier.booth_number'),
          key: 'store_warehouse_exhibition_id',
          minWidth: 150,
        },
        {
          title: $t('page.supplier.size'),
          key: 'size',
          minWidth: 150,
        },
        {
          title: $t('page.order.fee'),
          slot: "put_price",
          minWidth: 150,
        },
      ]
    },
  },
  watch: {
    tab: {
      handler() {
        this.getList();
      },
      immediate: true,
    },
  },
  methods: {
    async exportWarehouseBili(id) {
      try {
        this.loading = true;
        let res; // 在函数作用域声明
        // 1. 调用导出接口获取文件信息
        res = await exportWarehouseBillInfo(id);
        // 2. 检查响应是否成功
        if (res.code !== 0) {
          throw new Error(res.msg || '导出失败');
        }

        // 3. 获取文件信息
        const fileInfo = res.data;

        // 4. 使用文件URL下载文件
        await this.downloadFile(fileInfo);

        // 5. 显示成功消息
        this.$Message.success('导出成功，文件已开始下载');

      } catch (error) {
        // 错误处理
        this.$Message.error(error.message || '导出失败，请重试');
        console.error('导出错误:', error);
      } finally {
        this.loading = false;
      }
    },
    formattedDate(time) {
      const date = new Date(time);
      const year = date.getFullYear();
      // 注意：getMonth() 返回 0-11，所以要 +1
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    async exportBili(id) {
      try {
        this.exportLoading = true;
        let res; // 在函数作用域声明
        // 1. 调用导出接口获取文件信息
        res = await exportSupplierSummaryInfo(id);
        // 2. 检查响应是否成功
        if (res.code !== 0) {
          throw new Error(res.msg || '导出失败');
        }

        // 3. 获取文件信息
        const fileInfo = res.data;

        // 4. 使用文件URL下载文件
        await this.downloadFile(fileInfo);

        // 5. 显示成功消息
        this.$Message.success('导出成功，文件已开始下载');

      } catch (error) {
        // 错误处理
        this.$Message.error(error.message || '导出失败，请重试');
        console.error('导出错误:', error);
      } finally {
        this.exportLoading = false;
      }
    },
    async downloadFile(fileInfo) {
      try {
        // 1. 创建下载链接（优先使用 download_url，再使用 exports_url）
        // const downloadUrl = fileInfo.download_url || fileInfo.exports_url;
        const downloadUrl = fileInfo.exports_url;
        // 2. 创建隐藏的<a>标签触发下载
        const link = document.createElement('a');
        link.href = downloadUrl;

        // 从URL中提取文件名，或自定义文件名
        const fileName = downloadUrl.substring(downloadUrl.lastIndexOf('/') + 1);
        link.download = fileName; // 设置下载文件名

        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } catch (error) {
        console.error('文件下载错误:', error);
        throw new Error('文件下载失败: ' + error.message);
      }
    },
    confirm(row) {
      let delfromData = {
        title: "确认账单",
        url: `/finance/system_supplier_bill/set_status/${row.id}/3`,
        method: "PUT",
        ids: "",
        info:"确定确认账单吗",
        tips:  row.is_del ? '确定确认账单吗' : '确定确认账单吗',
      };
      this.$modalSure(delfromData)
          .then((res) => {
            this.$Message.success(res.msg);
            this.onchangeTime();
          })
          .catch((res) => {
            this.$Message.error(res.msg);
          });
    },
    formatTimeNative(timestamp) {
      const date = new Date(timestamp);
      const now = new Date();
      const isToday =
          date.getDate() === now.getDate() &&
          date.getMonth() === now.getMonth() &&
          date.getFullYear() === now.getFullYear();
      // 时间格式（小时:分钟 + am/pm）
      const timeOptions = {
        hour: 'numeric',
        minute: '2-digit',
        hour12: true,
      };
      const timeString = new Intl.DateTimeFormat('en-US', timeOptions).format(date);

      return isToday ? `Today at ${timeString}` : new Intl.DateTimeFormat('en-US', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: 'numeric',
        minute: '2-digit',
        hour12: true,
      }).format(date);
    },
    onClickTab(e) {
      this.tab = e;
    },
    GetSystemSupplierBillSettlementSummary(){
      this.loading = true;
      systemSupplierBillSettlementSummary({data:this.formValidate.data}).then((res) => {
        this.SettlementSummary = res.data.info
        this.sales_subtotal = 0
        this.costs_subtotal = 0

        for (let i = 0; i < this.SettlementSummary.system_supplier_bill_summary.length; i++) {
          if (this.SettlementSummary.system_supplier_bill_summary[i].type == "sales"){
            this.sales_subtotal += this.SettlementSummary.system_supplier_bill_summary[i].credits
          }else if (this.SettlementSummary.system_supplier_bill_summary[i].type == "costs"){
            this.costs_subtotal += this.SettlementSummary.system_supplier_bill_summary[i].debits
          }
        }

        this.loading = false;
      });
    },
    getList() {
      if (this.formValidate.detail_type == "" || this.formValidate.data == ""){
        return
      }
      this.loading = true;
      let data = {
        timeType: this.tab,
        detail_type:this.formValidate.detail_type,
        data: this.formValidate.data,
        page: this.formValidate.page,
        limit: this.formValidate.limit,
        id:this.SettlementSummary.id,
        warehouse_name:this.formValidate.warehouse_name,
      };
      systemSupplierBillSettlementSummaryList(data).then((res) => {
        this.orderList = res.data.list;
        this.loading = false;
        this.total = res.data.count;
      });
    },
    // 选择时间
    selectChange(tab) {
      this.formValidate.page = 1;
      this.formValidate.data = tab;
      this.timeVal = [];
      this.getList();
    },
    // 具体日期
    onchangeTime(e) {
      this.timeVal = e;
      this.formValidate.data = this.timeVal;
      this.GetSystemSupplierBillSettlementSummary();
      this.getList();
    },
    onchangeDetailType(){
      if (this.formValidate.detail_type == "order.income"){
        if  (this.infor.code.startsWith('B')){
          this.columns = this.orderIncomeBColumns
        }else{
          this.columns = this.orderIncomeAColumns
        }
      }else if (this.formValidate.detail_type == "storage.fee"){
        this.columns = this.storageFeeColumns
      }else if (this.formValidate.detail_type == "unloading.fee"){
        this.columns = this.unloadingFeeColumns
      }else if (this.formValidate.detail_type == "ob.fee"){
        this.columns = this.obFeeColumns
      }else if (this.formValidate.detail_type == "special.charges"){
        this.columns = this.specialFeeColumns
      }else if (this.formValidate.detail_type == "shownroom.fee"){
        this.columns = this.shownroomFeeColumns
      }
      this.getList();
    },
    //分页
    pageChange(page) {
      this.formValidate.page = page;
      this.getList();
    },
    // 账单详情
    Info(row) {
      this.$refs.commission.modals = true;
      this.$refs.commission.location_id = row.location_id
      this.$refs.commission.warehouse_type = this.SettlementSummary.system_supplier.warehouse_type
      this.$refs.commission.supplier_type = this.SettlementSummary.system_supplier.type
      this.$refs.commission.getList(row.id);
    },
    //下载
    async download(row) {
      let [th, filekey, data, fileName] = [[], [], [], ''];
      let excelData = { ids: row.ids, page: 1 };
      let lebData = await this.getExcelData(excelData);
      if (!fileName) {
        fileName = lebData.filename;
      }
      if (!filekey.length) {
        filekey = lebData.filekey;
      }
      if (!th.length) {
        th = lebData.header;
      }
      data = [...data, ...lebData.export];
      exportExcel(th, filekey, fileName, data);
    },
    getExcelData(excelData) {
      return new Promise((resolve) =>
        exportfundRecordApi(excelData).then((res) => resolve(res.data))
      );
    },
  },
  async mounted () {
    let storage=window.localStorage;
    let value = storage.getItem('userInfoSupplier')
    this.infor = JSON.parse(value);
  }
};
</script>

<style scoped lang="less">
/deep/.ivu-page-header,
/deep/.ivu-tabs-bar {
  border-bottom: 1px solid #ffffff;
}
/deep/.ivu-card-body {
  padding: 0;
}
/deep/.ivu-tabs-nav {
  height: 45px;
}

/deep/.ivu-tabs-bar {
  margin-bottom: 0px !important;
  border-bottom: 1px solid #e9e9e9 !important;
}
.tabbox {
  padding: 16px 20px 0px;
}
.box {
  padding: 20px;
  padding-bottom: 1px;
}
.tablebox {
  margin-top: 15px;
  padding-bottom: 10px;
}
.btnbox {
  padding: 20px 0px 0px 30px;
  .btns {
    width: 99px;
    height: 32px;
    background: #1890ff;
    border-radius: 4px;
    text-align: center;
    line-height: 32px;
    color: #ffffff;
    cursor: pointer;
  }
}
.table {
  padding: 0px 30px 15px 30px;
}
.section{
  padding: 25px 0;
  //border-bottom:1px dashed #EEEEEE
}

 .title{
   padding-left: 10px;
   border-left: 3px solid #1890FF;
   font-size: 15px;
   line-height: 15px;
   color: #303133;
 }


 .list {
   display: flex;
   align-items: center;
 }


 .item {
   flex: 0 0 calc(100% / 3);
   display: flex;
   margin-top: 16px;
   font-size: 13px;
 }

 .sales{
   display: flex; justify-content: center; align-items: center;text-align: center;padding: 10px 16px;
 }

 .sales-title {
   width: 60%;
   text-align: left;
 }

 .sales-debits{
   width: 20%;
 }
 .sales-credits{
   width: 20%;text-align: right;
 }
 .sales-bottom {
   position: absolute;bottom: 16px;width: 100%;
 }

.price-table {
  width: 100%;
  max-width: 800px;
  border-collapse: collapse;
  margin-bottom: 20px;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.price-table th,
.price-table td {
  padding: 12px 15px; /* 优化内间距，比原8px更舒适 */
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

.price-table th {
  background-color: #f7f9fc; /* 表头背景色区分 */
  font-weight: 600;
  color: #333;
  border-bottom: 2px solid #e5e9f2; /* 表头下边框加粗 */
}

.price-table tbody tr {
  transition: background-color 0.2s ease; /* 平滑过渡效果 */
}

.price-table tbody tr:hover {
  background-color: #fafbfc; /* 悬停行背景色变化 */
}

.price-table td:first-child {
  font-weight: 500; /* 第一列（类型）加粗突出 */
  color: #2c3e50;
}

.price-table td:not(:first-child) {
  color: #4a5568; /* 数值列颜色稍浅，突出类型列 */
}

/* 最后一行取消下边框，避免圆角被遮挡 */
.price-table tbody tr:last-child td {
  border-bottom: none;
}
</style>
